import {getRequset} from './api'

export const initMenus=(router,store) => {
    if(store.state.menu.routes && store.state.menu.routes.length > 0) {
        return;
    }
    getRequset("/system/config/menu").then(data => {
        if(data) {
            let fmtRoutes = formatRoutes(data);
            // console.log(JSON.stringify(fmtRoutes));
            router.selfaddRoutes(fmtRoutes);
            store.commit('initRoutes', fmtRoutes)
        }
    })
}

export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        if(children && children instanceof Array) {
            //递归赋值,组合成一个完整的router格式
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve) {
                if(component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'],resolve);
                }else if(component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'],resolve);
                }else if(component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'],resolve);
                }
            }
        }
        fmRoutes.push(fmRouter);
    });
    return fmRoutes;
}